#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/12 14:37
# @Author  : JY.Liu
# @Site    : http://github.com/lh1993
# @Mail    : lhln0119@163.com
# @File    : wechat.py
# @Software: PyCharm

import requests
import json
from aiohttp import ClientSession
from tools import get_config


class WeChatSent(object):

    def __init__(
            self,
            touser=get_config.touser,
            toparty=get_config.toparty,
            totag=get_config.totag,
            agentid=get_config.agentid):
        self.url = get_config.url
        self.touser = touser
        self.toparty = toparty
        self.totag = totag
        self.agentid = agentid

    def get_access_token(self):
        """
            获取XwjrRpc服务的公共资源接口
            如:企业微信access_token等
        """
        access_token = self.rpc_resource_pull('qyweixin_access_token')
        return access_token

    def rpc_resource_pull(self, resource_key):
        if resource_key is None or resource_key is '':
            return ''
        req_data = {
            'pull_resource': resource_key
        }
        res_data = requests.post(self.url, data=req_data)
        data_value = res_data.json()[resource_key]
        return data_value

    async def send_markdown(self, content):
        async with ClientSession() as session:
            access_token = self.get_access_token()
            url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % access_token
            data = {
                "touser": self.touser,
                "toparty": self.toparty,
                "totag": self.totag,
                "agentid": self.agentid,
                "msgtype": "markdown",
                "markdown": {
                    "content": content
                },
                "enable_duplicate_check": 0
            }
            # r = requests.post(url=url, data=json.dumps(data))
            # 采用 aiohttp，进行异步请求，使用await 将耗时等待的操作挂起，让出控制权
            r = await session.post(url=url, data=json.dumps(data))
            result = await r.json()
            return result
